import react from "@vitejs/plugin-react";
import dayjs from "dayjs";
import compresssionBuild from "rollup-plugin-compression";
import { fileURLToPath, URL } from "url";

// https://vitejs.dev/config/
export default async ({ mode }) => {
  const isDev = mode === "development";
  const isProd = mode === "production";

  const myDate = new Date();
  const nowDate = `${myDate.getFullYear()}-${myDate.getMonth() + 1}-${myDate.getDate()}_${myDate.getHours()}-${myDate.getMinutes()}`;

  return {
    base: "./",
    // 全局替换
    define: {
      "process.env.BUILD_TIME": `'${nowDate}'`,
    },

    build: {
      assetsInlineLimit: 0,
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: false,
          drop_debugger: true,
        },
      },
      chunkSizeWarningLimit: 0,
    },
    plugins: [
      react(),
      isProd &&
        compresssionBuild({
          sourceName: `dist`,
          type: "zip",
          targetName: `honghua_${nowDate}`,
        }),
    ],
    resolve: {
      alias: {
        "@hashHistory": fileURLToPath(
          new URL("./src/hashHistory", import.meta.url)
        ),
        "@utils": fileURLToPath(
          new URL("./src/utils/utils.ts", import.meta.url)
        ),
        "@views": fileURLToPath(new URL("./src/views", import.meta.url)),
        "@globalStore": fileURLToPath(
          new URL("./src/globalStore.ts", import.meta.url)
        ),
        "@components": fileURLToPath(
          new URL("./src/components", import.meta.url)
        ),
        "@api": fileURLToPath(new URL("./src/api", import.meta.url)),
        "@type": fileURLToPath(new URL("./src/type.ts", import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true, // 支持内联 javascript
        },
      },
    },
    server: {
      port: 5432,
      proxy: {
        "/api": {
          target: "http://jsonplaceholder.typicode.com",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
  };
};
